import { Icon, Input, Popover, Tree, Breadcrumb } from 'antd';
import React, { PureComponent } from 'react';
import router from 'umi/router';
import _ from 'lodash';
import { connect } from 'dva';
import generatePath from '@/utils/generatePath';

@connect(state => ({
  currentUser: state.user.currentUser.data,
}))
export default class ProjectsPath extends PureComponent {
  state = {
    treeData: [],
    expandedKeys: [],
    isEditingPath: false,
    autoExpandParent: false,
    searchValue: '',
    projectNode: {},
    level1Node: { orgname: '请选择项目' },
    level2Node: {},
  };

  componentDidMount() {
    if (
      this.props.match.params.stage ||
      (this.props.match.params.project && this.props.orgStructure.data.length > 0)
    ) {
      this.getPathInfo(this.props.orgStructure.data, this.props.match.params);
    }
  }

  componentWillReceiveProps(nextProps) {
    if (
      this.props.match.params.stage !== nextProps.match.params.stage ||
      this.props.match.params.project !== nextProps.match.params.project ||
      this.props.orgStructure.data !== nextProps.orgStructure.data
    ) {
      if (nextProps.orgStructure.data.length > 0) {
        this.getPathInfo(nextProps.orgStructure.data, nextProps.match.params);
      }
    }
  }

  getPathInfo = (orgStructure, params) => {
    const projectNode = this.findOrgStructureItem(orgStructure, params.project);

    if (!projectNode) {
      return;
    }
    const level1Node = this.findOrgStructureItem(orgStructure, params.level1);
    if (!level1Node) {
      return;
    }
    const level2Node = this.findOrgStructureItem(orgStructure, params.level2);
    if (!level2Node) {
      return;
    }

    this.setState({ projectNode, level1Node, level2Node, isEditingPath: false });
  };

  getTreeData = list => {
    let treeData = [];
    if (list && list.length > 0) {
      treeData = this.buildTree(list, '00000001');
    }
    this.setState({ treeData });
  };

  buildTree = (list, pid = '') => {
    const tree = [];
    list.forEach(value => {
      const x = value;
      if (`${x.parentOrgid}` === `${pid}`) {
        if (
          `${x.hrOrgTypeId}` !== '32' &&
          `${x.hrOrgTypeId}` !== '31' &&
          `${x.hrOrgTypeId}` !== '23'
        ) {
          x.children = [];
          x.selectable = false;
          // x.disabled = true;
          x.children = this.buildTree(list, x.orgdepid);
        }
        tree.push({
          ...x,
          key: x.orgdepid,
          value: x.orgdepid,
          title: x.orgname,
        });
      }
    });
    return tree;
  };

  onChangeProject = value => {
    const projectNode = this.findOrgStructureItem(this.props.orgStructure.data, value);
    if (!projectNode) {
      return;
    }
    const level2Node = this.findOrgStructureItem(
      this.props.orgStructure.data,
      projectNode.parentOrgid,
    );
    if (!level2Node) {
      return;
    }
    const level1Node = this.findOrgStructureItem(
      this.props.orgStructure.data,
      level2Node.parentOrgid,
    );
    if (!level1Node) {
      return;
    }

    // 判断项目下有没有分期
    // const stages = this.findOrgStructureChildren(
    //   this.props.orgStructure.data,
    //   projectNode.orgdepid,
    // );
    // if (stages && stages.length > 0) {
    let path = this.props.match.path.split('/:level1')[0];
    path =
      path.search('EntireProject') > -1 ||
      path.search('ConfirmProject') > -1 ||
      path.search('PayBackModulus') > -1 ||
      path.search('GroupApproveVersion') > -1
        ? `${path}/:level1/:level2/:project`
        : `${path}/EntireProject/:level1/:level2/:project`;
    const { alias } = this.props.currentUser;
    const localStorageProjects = localStorage.getItem('projects');
    const projects = JSON.parse(localStorageProjects) || {};
    projects[`${alias}`] = {
      level1: level1Node.orgdepid,
      level2: level2Node.orgdepid,
      project: projectNode.orgdepid,
    };

    localStorage.setItem('projects', JSON.stringify(projects));

    router.replace(
      generatePath(path, {
        ...this.props.match.params,
        level1: level1Node.orgdepid,
        level2: level2Node.orgdepid,
        project: projectNode.orgdepid,
      }),
    );
    // }
    this.setState({ projectNode, value, level1Node, level2Node, isEditingPath: false });
  };

  findOrgStructureItem = (orgStructure, id) => {
    const filteredItems = _.filter(orgStructure, item => `${item.orgdepid}` === `${id}`);
    if (filteredItems && filteredItems.length > 0) {
      return filteredItems[0];
    }
    return null;
  };

  findOrgStructureChildren = (orgStructure, pid) => {
    const filteredItems = _.filter(orgStructure, item => `${item.parentOrgid}` === `${pid}`);
    return filteredItems;
  };

  getParentKey = (key, tree) => {
    let parentKey;
    // eslint-disable-next-line  no-plusplus
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i];
      if (node.children) {
        if (node.children.some(item => item.key === key)) {
          parentKey = node.key;
        } else if (this.getParentKey(key, node.children)) {
          parentKey = this.getParentKey(key, node.children);
        }
      }
    }
    return parentKey;
  };

  onSearch = value => {
    // 11 旭辉集团,20 事业部/区域集团,21 城市公司,23 直管项目,31 项目,32 分期
    // 筛选出除了项目级一下的所有数据
    const filterList = _.filter(
      this.props.orgStructure.data,
      x =>
        x.hrOrgTypeId === '11' ||
        x.hrOrgTypeId === '20' ||
        x.hrOrgTypeId === '21' ||
        x.hrOrgTypeId === '23' ||
        x.hrOrgTypeId === '31',
    );
    const searchDate = _.filter(
      filterList,
      val => _.toUpper(_.trim(val.orgname)).indexOf(_.toUpper(_.trim(value))) > -1,
    );
    let ids = [];

    const orgStructure = [];
    _.forEach(searchDate, val => {
      _.forEach(val.orgnofullpath.split('-'), data => {
        ids.push(data);
      });
    });
    ids = _.uniq(ids);
    _.forEach(this.props.orgStructure.data, val => {
      _.forEach(ids, data => {
        if (val.orgdepid === data) {
          orgStructure.push(val);
        }
      });
    });
    this.setState({
      expandedKeys: value ? ids : [],
      autoExpandParent: false,
    });
    this.getTreeData(orgStructure);
  };

  onExpand = expandedKeys => {
    this.setState({
      expandedKeys,
      autoExpandParent: false,
    });
  };

  render() {
    const { edit, stage } = this.props.match.params;
    const { isEditingPath, expandedKeys, autoExpandParent } = this.state;
    if (edit && !_.isEmpty(this.props.orgStructure.data)) {
      return (
        <Breadcrumb className="title">
          <Breadcrumb.Item>
            {this.state.projectNode.orgname}(
            {`${_.filter(this.props.orgStructure.data, { orgdepid: stage })[0].orgname}`})
          </Breadcrumb.Item>
          <Breadcrumb.Item>{this.props.editName || '编制'}</Breadcrumb.Item>
        </Breadcrumb>
      );
    }
    localStorage.setItem('orgname', this.state.projectNode.orgname);
    return (
      <div style={{ cursor: 'pointer' }}>
        {/* TODO 获取当前角色 */}
        <Popover
          placement="topLeft"
          content={
            <>
              <Input.Search
                style={{ marginBottom: 8 }}
                placeholder="请输入关键字"
                onSearch={value => this.onSearch(value)}
              />
              <Tree
                style={{ maxHeight: 300, overflow: 'auto' }}
                value={this.state.value}
                searchValue={this.state.searchValue}
                dropdownStyle={{ maxHeight: 500, overflow: 'auto' }}
                treeData={this.state.treeData}
                treeNodeFilterProp="title"
                expandedKeys={expandedKeys}
                onExpand={this.onExpand}
                autoExpandParent={autoExpandParent}
                onSearch={value => {
                  this.setState({
                    searchValue: value,
                  });
                }}
                placeholder="请选择项目"
                onSelect={this.onChangeProject}
              />
            </>
          }
          trigger="click"
          visible={this.state.isEditingPath}
          onVisibleChange={() => {
            this.setState({ isEditingPath: !isEditingPath });
            this.getTreeData(this.props.orgStructure.data);
          }}
        >
          <Breadcrumb>
            <Breadcrumb.Item>{this.state.level1Node.orgname}</Breadcrumb.Item>
            <Breadcrumb.Item>{this.state.level2Node.orgname}</Breadcrumb.Item>
          </Breadcrumb>
          <div style={{ fontSize: '14px' }}>
            {this.state.projectNode.orgname}&nbsp;
            <Icon type={!isEditingPath ? 'down' : 'up'} size="small" />
          </div>
        </Popover>
      </div>
    );
  }
}
